/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { BidirectionalMap } from '../util/bidirectional-map.js';

// 线程ThreadId = `${processId}@${workerId}`
export type ThreadId = string | undefined;
export type SocketId = string;

/**
 * 存储socket与thread映射关系的映射表
 */
export class SessionMap {
  private readonly sessionMap: BidirectionalMap<SocketId, ThreadId>;

  constructor() {
    this.sessionMap = new BidirectionalMap<SocketId, ThreadId>();
  }

  public getSocketId(threadId: ThreadId) {
    return this.sessionMap.getByValue(threadId);
  }

  public getThreadId(socketId: SocketId) {
    return this.sessionMap.getByKey(socketId);
  }

  public setSession(socketId: SocketId, threadId: ThreadId) {
    if (this.sessionMap.checkByKey(socketId)) {
      this.sessionMap.deleteByKey(socketId);
    }
    if (this.sessionMap.checkByValue(threadId)) {
      this.sessionMap.deleteByValue(threadId);
    }
    this.sessionMap.set([socketId, threadId]);
  }

  public deleteByThreadId(threadId: ThreadId) {
    this.sessionMap.deleteByValue(threadId);
  }

  public deleteBySocketId(socketId: SocketId) {
    this.sessionMap.deleteByKey(socketId);
  }

  public checkBySocketId(socketId: SocketId): boolean {
    return this.sessionMap.checkByKey(socketId);
  }

  public checkByThreadId(threadId: ThreadId): boolean {
    return this.sessionMap.checkByValue(threadId);
  }
}

export function getThreadId(workerProcessId: number, workerThreadId: number): ThreadId {
  return `${workerProcessId}@${workerThreadId}`;
}

export function resolveThreadId(threadId: string) {
  return threadId.split('@').map((str) => parseInt(str));
}
